<template>
  <PageWrapper content-full-height fixed-height dense>
    <AdVxeTable @register="registerTable">
      <template #tools>
        <Authority value="Root.Report.Admin.Sheet.Create">
          <a-button type="primary" @click="handleCreate">
            <Icon icon="ant-design:plus-circle-outlined" />{{ t('common.addText') }}
          </a-button>
        </Authority>
      </template>

      <template #actionCol="{ row }">
        <TableAction
          outside
          :actions="[
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: t('common.delText'),
              auth: 'Root.Report.Admin.Sheet.Delete', // 权限控制
              // ifShow: (_action) => {
              //   return row?.Deletable === true; // 根据业务控制是否显示: 是否可删除的数据权限状态
              // },
              popConfirm: {
                title: t('common.delConfirmText'),
                placement: 'left',
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
          :drop-down-actions="[
            {
              icon: 'lucide:view',
              label: t('common.previewText'),
              onClick: handleView.bind(null, row),
            },
            {
              icon: 'clarity:note-edit-line',
              label: t('common.editText'),
              auth: 'Root.Report.Admin.Sheet.Update', // 权限控制
              // ifShow: (_action) => {
              //   return row?.Updatable === true; // 根据业务控制是否显示: 是否可更新的数据权限状态
              // },
              onClick: handleEdit.bind(null, row),
            },
            {
              icon: 'carbon:user-role',
              label: t('report.route.report.roleAssign'),
              auth: ['Root.Report.Admin.Sheet.SetRoles'], // 权限控制
              onClick: handleSetRolesModalOpen.bind(null, row),
            },
            {
              icon: 'la:user-cog',
              label: t('report.route.report.userAssign'),
              auth: ['Root.Report.Admin.Sheet.SetUsers'], // 权限控制
              onClick: handleSetUsersModalOpen.bind(null, row),
            },
          ]"
        />
      </template>
    </AdVxeTable>

    <RoleTransferModal
      @register="registerSetRolesModal"
      :title="t('report.route.report.roleAssign')"
      :search="true"
      :close-func="handleSetRolesModalClose"
      :ok-text="t('common.updateText')"
      :ok-authority="true"
      ok-authority-code="Root.Report.Admin.Kanban.SetRoles"
      :ok-func="handleSetRolesModalOk"
      width="50%"
    />
    <UserTransferModal
      @register="registerSetUsersModal"
      :title="t('report.route.report.userAssign')"
      :search="true"
      :close-func="handleSetUsersModalClose"
      :ok-text="t('common.updateText')"
      :ok-authority="true"
      ok-authority-code="Root.Report.Admin.Kanban.SetUsers"
      :ok-func="handleSetUsersModalOk"
      width="50%"
    />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import {
    deleteSheet,
    readSheetRoles,
    readSheetSimple,
    readSheetUsers,
    setSheetRoles,
    setSheetUsers,
  } from '@/api/report/admin/sheet';
  import { useModal } from '@/components/AdVxeModal';
  import { AdVxeTable, TableAction, useAdVxeTable } from '@/components/AdVxeTable';
  import { Authority } from '@/components/Authority';
  import Icon from '@/components/Icon/Icon.vue';
  import { PageWrapper } from '@/components/Page';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';
  import { router } from '@/router';
  import RoleTransferModal from '@/views/system/identity/role/RoleTransferModal.vue';
  import UserTransferModal from '@/views/system/identity/user/UserTransferModal.vue';

  import { columns } from './sheet.data';

  defineOptions({ name: 'SheetPage' });

  const { t } = useI18n();
  const { createMessage } = useMessage();

  const [registerTable, { reload: reloadTable }] = useAdVxeTable({
    id: 'report-sheet-page-table',
    // 表标题呈现器
    title: t('report.route.report.sheet.list'),
    // 表格数据接口请求对象
    api: readSheetSimple,
    // 详情表单
    // detailForm: {
    //   // 表单标识
    //   formIndex: 'report_dblink_detail',
    //   // 主键字段
    //   keyField: 'Id',
    //   // 详情表单抬头
    //   title: t('report.route.report.sheet.title'),
    //   // 实体新增接口请求对象
    //   createApi: createDbLink,
    //   // 实体更新接口请求对象
    //   updateApi: updateDbLink,
    // },
    // 表单列信息 AdColumn[]
    columns,
    // 使用搜索表单
    searchForm: true,
    // 是否带有边框 boolean | default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
    border: false,
    // 是否显示序号列
    showSeqColumn: true,
    // 表格右侧操作列配置 AdColumn
    actionColumn: {
      width: 80,
      title: t('common.actionText'),
      fixed: 'right',
      slots: { default: 'actionCol' },
    },
  });

  /** 处理创建 */
  async function handleCreate() {
    const routeUrl = router.resolve({
      path: '/report/sheet/designer',
      // query: {
      //   id: 'designer',
      // },
    });
    window.open(routeUrl.href, '_blank');
  }
  /** 处理查看 */
  async function handleView(record: any) {
    const routeUrl = router.resolve({
      path: '/report/sheet/viewer',
      query: {
        id: record.Id,
      },
    });
    window.open(routeUrl.href, '_blank');
  }
  /** 处理编辑 */
  async function handleEdit(record: any) {
    const routeUrl = router.resolve({
      path: '/report/sheet/designer',
      query: {
        id: record.Id,
      },
    });
    window.open(routeUrl.href, '_blank');
  }
  /** 处理删除 */
  async function handleDelete(record: any) {
    const result = await deleteSheet([record.Id]);
    if (result.Succeeded) {
      createMessage.success(t('common.successText'));
      reloadTable();
    }
  }

  // #region "设置角色-弹窗穿梭框"
  const [registerSetRolesModal, setRolesModalMethods] = useModal();
  /** 处理打开设置角色弹窗 */
  async function handleSetRolesModalOpen(record: any) {
    if (record && record.Id) {
      const roleNodes = await readSheetRoles(record.Id);

      setRolesModalMethods.openModal(true, {
        roleNodes,
        record,
      });
      setRolesModalMethods.setModalProps({
        title: `${t('report.route.report.roleAssign')} - ${record.Name}`,
      });
    }
  }
  /** 处理设置角色弹窗关闭按钮 */
  async function handleSetRolesModalClose() {
    return true;
  }
  /** 处理设置角色弹窗确定按钮 */
  async function handleSetRolesModalOk(targetKeys: (bigint | string)[], roleNodes: any[], record: any) {
    if (targetKeys && roleNodes && record && record.Id) {
      const checkedKeys = targetKeys;
      if (checkedKeys) {
        const roleIds = checkedKeys;
        const result = await setSheetRoles({ SheetId: record.Id, RoleIds: [...roleIds] });
        if (result.Succeeded) {
          createMessage.success(t('common.successText'));
          reloadTable();
          return true;
        } else {
          return false;
        }
      }
      return true;
    } else {
      return true;
    }
  }
  // #endregion

  // #region "设置用户"
  const [registerSetUsersModal, setUsersModalMethods] = useModal();
  /** 处理打开设置角色弹窗 */
  async function handleSetUsersModalOpen(record: any) {
    if (record && record.Id) {
      const userNodes = await readSheetUsers(record.Id);

      setUsersModalMethods.openModal(true, {
        userNodes,
        record,
      });
      setUsersModalMethods.setModalProps({
        title: `${t('report.route.report.userAssign')} - ${record.Name}`,
      });
    }
  }
  /** 处理设置角色弹窗关闭按钮 */
  async function handleSetUsersModalClose() {
    return true;
  }
  /** 处理设置角色弹窗确定按钮 */
  async function handleSetUsersModalOk(targetKeys: (bigint | string)[], roleNodes: any[], record: any) {
    if (targetKeys && roleNodes && record && record.Id) {
      const checkedKeys = targetKeys;
      if (checkedKeys) {
        // console.log(checkedKeys);
        const userIds = checkedKeys;
        const result = await setSheetUsers({ SheetId: record.Id, UserIds: [...userIds] });
        if (result.Succeeded) {
          createMessage.success(t('common.successText'));
          reloadTable();
          return true;
        } else {
          return false;
        }
      }
      return true;
    } else {
      return true;
    }
  }
  // #endregion
</script>
